package org.redis.cluster.auth;

import org.apache.commons.lang3.StringUtils;
import org.redis.cluster.Ordered;
import org.redis.cluster.RedisCluster;
import org.redis.cluster.interceptor.Interceptor;
import org.redis.cluster.interceptor.Invocation;
import org.redis.cluster.plugin.Plugin;
import org.redis.cluster.redis.RedisCommand;
import org.redis.cluster.redis.transport.RedisReply;
import org.redis.cluster.redis.transport.reply.RedisErrorReply;
import org.redis.cluster.transport.session.Session;

public class AuthInterceptor implements Plugin,Interceptor,Ordered {
	
	private RedisCluster redisCluster;
	private String password;
	
	@Override
	public void init(RedisCluster redisCluster) {
		this.redisCluster=redisCluster;
		this.password=initPassword();
	}
	
	protected String initPassword() {
		return AuthHelper.getPassword(redisCluster);
	}
	
	@Override
	public void destroy() {
	}

	@Override
	public RedisReply intercept(Invocation invocation) throws Throwable {
		RedisCommand command=invocation.getCommand();
		if(StringUtils.isBlank(password) || isAuthCommand(command)) {
			return invocation.invoke();
		}

		Session session=invocation.getSession();
		if(!AuthHelper.isAuth(session, password)) {
			return new RedisErrorReply("ERR operation not permitted");
		}
		
		return invocation.invoke();
	}

	@Override
	public int getOrder() {
		return Ordered.HIGH;
	}
	
	protected boolean isAuthCommand(RedisCommand command) {
		return command.getCommand().equals(AuthConstants.COMMAND);
	}
	
	public void setRedisCluster(RedisCluster redisCluster) {
		this.redisCluster = redisCluster;
	}
	public RedisCluster getRedisCluster() {
		return redisCluster;
	}
}